package com.cn.lp.ai.factory;

import org.springframework.ai.chat.client.AdvisedRequest;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ResourceChatMemoryAdvisor extends AbstractChatMemoryAdvisor<ChatMemory> {
    public ResourceChatMemoryAdvisor(ChatMemory chatMemory) {
        super(chatMemory);
    }

    public ResourceChatMemoryAdvisor(ChatMemory chatMemory, String defaultConversationId, int chatHistoryWindowSize) {
        super(chatMemory, defaultConversationId, chatHistoryWindowSize);
    }

    public AdvisedRequest adviseRequest(AdvisedRequest request, Map<String, Object> context) {
        String conversationId = this.doGetConversationId(context);
        int chatMemoryRetrieveSize = this.doGetChatMemoryRetrieveSize(context);
        List<Message> memoryMessages = ((ChatMemory)this.getChatMemoryStore()).get(conversationId, chatMemoryRetrieveSize);
        List<Message> advisedMessages = new ArrayList(request.messages());
        advisedMessages.addAll(memoryMessages);
        AdvisedRequest advisedRequest = AdvisedRequest.from(request).withMessages(advisedMessages).build();
        UserMessage userMessage = new UserMessage(request.userText(), request.media());
        ((ChatMemory)this.getChatMemoryStore()).add(this.doGetConversationId(context), userMessage);
        return advisedRequest;
    }

}